import { defineStore } from 'pinia'
import { ref } from 'vue'
import Cookies from 'js-cookie'
import { getCustomerMenu, getTemplateHooks } from '@/api/common'
import { getPlaid } from '@/utils/auth'

export const useAppStore = defineStore('app', () => {
  // state
  const sidebar = ref({
    opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
    withoutAnimation: false
  })
  const device = ref('desktop')
  const customerMenu = ref([])
  const layout = ref('')
  const hooks = ref({})
  const hooksLoading = ref(true)

  // actions
  const toggleSideBar = () => {
    sidebar.value.opened = !sidebar.value.opened
    sidebar.value.withoutAnimation = false
    if (sidebar.value.opened) {
      Cookies.set('sidebarStatus', '1')
    } else {
      Cookies.set('sidebarStatus', '0')
    }
  }

  const closeSideBar = (withoutAnimation) => {
    Cookies.set('sidebarStatus', '0')
    sidebar.value.opened = false
    sidebar.value.withoutAnimation = withoutAnimation
  }

  const toggleDevice = (val) => {
    device.value = val
  }

  const setLayout = (val) => {
    layout.value = val
  }

  const setCustomerMenu = (menu) => {
    customerMenu.value = menu
  }

  const setHooks = (hookData) => {
    hooks.value = hookData
  }

  const setHooksLoading = (loading) => {
    hooksLoading.value = loading
  }

  // 获取用户菜单信息
  const getCustomerMenuAction = () => {
    return new Promise((resolve, reject) => {
      getCustomerMenu()
        .then((res) => {
          setCustomerMenu(res.data)
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  // 获取模板钩子内容
  const getTemplateHooksAction = () => {
    return new Promise((resolve, reject) => {
      hooksLoading.value = true
      const plaid = getPlaid()

      getTemplateHooks({
        dkSys: {
          plaid
        }
      })
        .then((res) => {
          setHooks(res.data || {})
          hooksLoading.value = false
          resolve(res)
        })
        .catch((error) => {
          hooksLoading.value = false
          reject(error)
        })
    })
  }

  return {
    sidebar,
    device,
    customerMenu,
    layout,
    hooks,
    hooksLoading,
    toggleSideBar,
    closeSideBar,
    toggleDevice,
    setLayout,
    setCustomerMenu,
    getCustomerMenuAction,
    setHooks,
    setHooksLoading,
    getTemplateHooksAction
  }
})
